package cn.iphone.controller;

import cn.iphone.domain.User;
import cn.iphone.fegin.UserService;
import cn.iphone.sentinel.GetByIdBlockHandlerClass;
import cn.iphone.sentinel.GetByIdFallbackClass;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/order")
// 动态刷新配置注解
@RefreshScope
public class OrderController {
    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    @SentinelResource(
    value = "order-getById",
    blockHandler = "getByIdBlockHandler",
    blockHandlerClass = GetByIdBlockHandlerClass.class,
    fallback = "getByIdFallback",
    fallbackClass = GetByIdFallbackClass.class)


    public User getById(@PathVariable("id") Long id){
        int i = 1 / 0;	//方法异常，触发熔断
        return userService.getById(id);
    }

    /**
     * 本类限流
     * @param id
     * @return
     */
    public User getByIdBlockHandler(@PathVariable("id") Long id, BlockException blockException){
        blockException.printStackTrace();
        return new User(-1L,"限流啦！");
    }

    /**
     * 本类熔断
     * @param id
     * @return
     */
    public User getByIdFallback(@PathVariable("id") Long id, Throwable throwable){
        throwable.printStackTrace();
        return new User(-1L,"熔断啦！");
    }

}